<template>
  <div>
    <van-cell
      :title="text"
      icon="search"
      v-for="(text, index) in suggestions"
      :key="index"
      @click="$emit('search', text)"
    >
      <div slot="title" v-html="highLight(text)"></div>
    </van-cell>
    <!-- <div>{{ str }}</div> -->
    <!-- <div v-html="str"></div> -->
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search'
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      suggestions: [],
      // str: 'Hello,<span style="color:red">World</span>',
    }
  },
  computed: {},
  watch: {
    searchText: {
      handler: debounce(function(val) {
        this.loadSearchSuggestions(val)
      }, 400),
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    async loadSearchSuggestions(val) {
      try {
        const { data } = await getSearchSuggestions(val)
        // console.log(data)
        this.suggestions = data.data.options
      } catch (err) {
        this.$toast('获取数据失败，请稍后重试')
      }
    },
    highLight(text) {
      const reg = RegExp(this.searchText, 'gi')
      const highlightStr = `<span style="color:red">${this.searchText}</span>`
      return text.replace(reg, highlightStr)
    },
  },
}
</script>

<style lang="less" scoped></style>
